﻿/// <reference path="jquery.js" />
/// <reference path="custom2.js" />
/// <reference path="errorcode.js" />
//
//验证类v1.1
//李杰 2013.10.2
//qq:473084
function Validated()
{
    this.rules={};
}
//从表单增加规则
//form  jquery表单元素对象，如果省略则使用body元素
/* 
规则对象格式
"name": {
"data": /^.{2,45}$/|function(){}|ture|false,  //支持任何表达式
"complete": "ok",
"error": "广告名称不得少于2个字符",
"normal": "请输入广告名称",
"required": true,  
"remote":true 
}
*/
Validated.prototype={
    rules: {},
    errmsg: "",
    addrule: function(rule)
    {
        for(var key in rule) {
            this.rules[key]=rule[key];
        }
        return this;
    },
    remove: function(keys)
    {
        var _t=this;
        keys=keys.split(",");
        $.each(keys,function(i,value)
        {
            if(_t.rules[value]) {
                delete _t.rules[value];
            }
        });
    },
    refresh: function()
    {
        var _t=this;
        $.each(this.rules,function(k,v)
        {
            if($("#"+k).length==0) {
                delete _t.rules[k];
            }
        });
    },
    validate: function(key,val)
    {
        val=val||$("#"+key).val()||$("#"+key).text().replace(/\s+/img,"");
        var config=this.rules[key];
        config["value"]=val;
        if(config["required"]!==false||val) {
            var rule=config.data;
            switch(rule.constructor) {
                case RegExp:
                    rule=val.match(rule);
                    break;
                case Function:
                    rule=rule(key);
                    break;
            }
            if(rule&&this.rules[key]["remote"]!==false) {
                this.succeed(key);
            }
            else {
                this.error(key);
            }
            return rule
        }
        return true;
    },
    bind: function(event,func)
    {
        var t=this;
        $.each(this.rules,function(k,v)
        {
            var key=$("#"+k);
            if(key.length) {
                key.unbind(event,func);
                key.bind(event,func);
            }
            else {
                delete t[k];
            }
        });
        return this;
    },
    event: function(key,event)
    {
        var t=this;
        if(this.rules[key]) {
            $("#"+key).bind(event,function()
            {
                t.validate(this.id);
            });
        }
    },
    normal: function(key,empty)
    {
        var info=$("[for="+key+"]");
        info.html(empty?"":this.rules[key]["normal"]||"");
        info.removeClass("succeed");
        info.removeClass("error");
        info.addClass("normal");
        return this;
    },
    onsucceed: function(key)
    {

    },
    succeed: function(key)
    {
        var info=$("[for="+key+"]");
        if(info.length) {
            if(info[0].tagName.toLowerCase()!="input") {
                info.html("&nbsp;"+(this.rules[key].complete||""));
            }
            info.removeClass("error");
            info.removeClass("normal");
            info.addClass("succeed");
        }
        this.rules[key]["succeed"]=true;
        this.onsucceed(key);
        return this;
    },
    onerror: function(key)
    {

    },
    error: function(key,msg)
    {
        var info=$("[for="+key+"]");
        msg=msg||this.rules[key]["remotemsg"]||this.rules[key].error||"出错了！";
        if(info.length) {
            this.infoval(info,msg);
            info.removeClass("succeed");
            info.removeClass("normal");
            info.addClass("error");
            this.rules[key]["succeed"]=false;
        }
        this.onerror(key,msg);
        return this;
    },
    remote: function(key,status,msg)
    {
        this.rules[key]["remotemsg"]=msg;
        switch(arguments.length) {
            case 1:
                this.rules[key]["remote"]=false;
                break;
            case 2:
                this.rules[key]["remote"]=status;
                break;
            case 3:
                if(status) {
                    this.succeed(key);
                    this.rules[key]["remote"]=true;
                }
                else {
                    this.error(key,msg);
                }
                break;
        }
    },
    infoval: function(info,msg)
    {
        info.addClass("normal");
        if(info[0].tagName.toLowerCase()=="input") {
            info.val(msg||"");
        }
        else {
            info.html(msg||"");
        }
    },
    initdef: function(holder)
    {
        if(holder) {
            for(var key in this.rules) {
                var info=$("#"+key);
                info.attr("placeholder",this.rules[key].normal)
            }
        }
        else {
            for(var key in this.rules) {
                var info=$("[for="+key+"]");
                if(info.length&&$("#"+key).val()=="") {
                    this.infoval(info,this.rules[key].normal);
                }
            }
        }
        return this;
    },
    blur: function()
    {
        var _t=this;
        this.bind("blur",function()
        {
            _t.validate(this.id);
        });
        return this;
    },
    focus: function(empty)
    {
        var _t=this;
        this.bind("focus",function()
        {
            _t.normal(this.id,empty);
        });
        return this;
    },
    ajaxverify: function(params,url)
    {
        var t=this;
        url=url||"/data/ajaxverify.aspx";
        params=params||{};
        if(Cookie.Get("usertoken")) {
            params["usertoken"]=Cookie.Get("usertoken");
        }
        $.post(url,params,function(data)
        {
            data=data.toJson();
            if(t.onajaxverify) {
                t.onajaxverify(data);
            }
            else {
                t.remote(data["jsonmarker"],data["data"],errorcode[data["data"]]);
            }
        });
        return this;
    },
    onajaxverify: null,
    //完整的验证，即验证指定或所有的
    complete: function(keys)
    {
        this.refresh();
        if(keys) {
            var len=arguments.length;
            for(var i=0;i<len;i++) {
                if(!this.validate(arguments[i])||this.rules[arguments[i]]["remote"]===false) {
                    this.errmsg=this.rules[arguments[i]].error;
                    return false;
                }
            }
        }
        else {
            for(var key in this.rules) {
                if(!this.validate(key)||this.rules[key]["remote"]===false) {
                    this.errmsg=this.rules[key].error;
                    return false;
                }
            }
        }
        return this.oncomplete();
    },
    oncomplete: function()
    {
        return true;
    },
    trigger: function(el,event)
    {
        var _t=this;
        $(el).bind(event,function(e)
        {
            if(!_t.complete()) {
                e.preventDefault();
            }
        });
    }
}
Validated.mailrule=/^[\w\-_]{1,20}@([\w\-]{1,10}){1,3}(\.[\w\-]{1,10}){1,3}$/img;
Validated.phonerule=/^0?1[1-9]\d{9}$/;
Validated.fixedphonerule=/^\d{3,4}-?\d{7,8}-?\d{0,8}$/;
Validated.qqrule=/^[1-9]\d{4,11}$/;
Validated.daterule=/^\d{4}-\d{2}-\d{2}(\s\d{2}:\d{2}(:\d{2})?)?$/;
Validated.idcard=/^\d{17}[\dx]$/i;
Validated.dbletter=/^[\u4e00-\u9fa5]+$/
Validated.moneyrule=/^(0|[1-9]\d{0,8})(?:\.\d{1,2})?$/
Validated.Rules={};

Validated.number=function(val,min,max)
{
    return val.constructor==Number&&val>=min&&val<=max;
}
Validated.numberkey=function(key,min,max)
{
    var el=$("#"+key);
    var min=el.attr("min")?parseFloat(el.attr("min")):min;
    var max=el.attr("max")?parseFloat(el.attr("max")):max;
    var val=parseFloat(el.val());
    return Validated.number(val,min,max);
}
Validated.money=function(key)
{
    return Validated.numberkey(key,-Math.pow(10,12)+1,Math.pow(10,12)-1);
}
Validated.tinyint=function(key)
{
    return Validated.numberkey(key,0,255);
}
Validated.smallint=function(key)
{
    return Validated.numberkey(key,-32768,32767);
}
Validated.int=function(key)
{
    return Validated.numberkey(key,-2147483648,2147483647);
}
Validated.bigint=function(key)
{
    return Validated.numberkey(key,-9223372036854775808,9223372036854775807);
}
Validated.float=function(key)
{
    var t=Math.pow(10,38);
    return Validated.numberkey(key,-t+1,t-1);
}
Validated.datetimekey=function(key,min,max)
{
    var el=$("#"+key);
    var min=el.attr("min")||min;
    var max=el.attr("max")||max;
    var val=Date.parse(el.val());
    return Validated.number(val,Date.parse(min),Date.parse(max));
}
Validated.datetime=function(key)
{
    return Validated.datetimekey(key,"1700-01-01","9999-12-30");
}
Validated.string=function(val,minlength,maxlength)
{
    return new RegExp("^\.{"+minlength+","+maxlength+"}$","img").test(val);;
}
Validated.varcharkey=function(key,minlength,maxlength)
{
    var el=$("#"+key);
    var min=el.attr("minlength")||minlength;
    var max=el.attr("maxlength")||maxlength;
    return Validated.string(el.val(),min,max);
}
Validated.varchar=function(key)
{
    return Validated.varcharkey(key,0,4000);
}